package com.shipwe.loans.ui.fragment

import android.view.LayoutInflater
import android.view.View
import com.shipwe.loans.R
import com.shipwe.loans.databinding.FragmentOrderPayPinProcessBinding
import com.shipwe.loans.pro.ShipweFragment
import com.shipwe.loans.ui.activity.ActivityOrderPayPin
import com.shipwe.loans.utils.event.AppEventPointType
import com.shipwe.loans.utils.thread.TimingThread
import org.json.JSONObject

/**
 * Shipwe
 * @Author wwdeng
 * @CreateTime: 2024/11/27 17:04
 * @Annotation：支付结果处理中
 */
class FragmentOrderPayPinProcess(): ShipweFragment(), TimingThread.ITimingThreadListener {
    lateinit var binding: FragmentOrderPayPinProcessBinding
    private var orderData: JSONObject? = null
    private var act: ActivityOrderPayPin? = null
    //倒计时
    private var countdown = 30
    private var timeThread: TimingThread? = null

    constructor(act: ActivityOrderPayPin, data: JSONObject): this(){
        this.act = act
        this.orderData = data
    }
    override fun getShipweRootView(inflater: LayoutInflater): View {
        binding = FragmentOrderPayPinProcessBinding.inflate(inflater)
        return binding.root
    }

    override fun initShipweView() {
        rootViewBinding.rootLayout.setBackgroundResource(R.drawable.page_login_bg)
        setShipweTitleBarVisibility(View.VISIBLE)
        setShipweTextTitle(getString(R.string.loan_payment_status_title))
        setShipweRightBtnRes(R.drawable.customer_black)
    }

    override fun initShipweListener() {
        //客服
        rootViewBinding.rootCustomer.setOnClickListener {
            if (act != null){
                showCustomerDialog("PIN PaymentProcess Page",act!!.getOrderPayProductName(),act!!.getOrderPayProductToken())
            }
            appEventPointRequestAction(AppEventPointType.CLICK.SHIPWE_CLICK_CUSTOMER,"PIN PaymentProcess Page")
        }
        //刷新
        binding.orderPayProcessRefreshViewGroup.setOnClickListener {
            if (orderData != null){
                appEventPointRequestAction(AppEventPointType.CLICK.SHIPWE_CLICK_LOAN_PAYMENT_PROCESS_PAYMENT_UPDATE,"TransactionId：${orderData!!.optString("transactionId")}")
            }
            if (act != null){
                //再次调用查询状态接口
                act!!.presenter!!.loadOrderPaymentPinStatusAction()
            }
        }

        //再次还款
        binding.orderPayProcessPaymentAgain.setOnClickListener {
            if (orderData != null){
                appEventPointRequestAction(AppEventPointType.CLICK.SHIPWE_CLICK_LOAN_PAYMENT_PROCESS_PAYMENT_AGAIN,"TransactionId：${orderData!!.optString("transactionId")}")
            }
            if (act != null){
                act!!.presenter!!.loadOrderPayLinkAction()
            }
        }
    }

    override fun initShipweData() {
        if (orderData != null){
            refreshOrderPayProcessData(this.orderData!!)
        }
    }

    /**
     * 刷新数据
     */
    private fun refreshOrderPayProcessData(data: JSONObject){
        this.orderData = data
        val realRepayAmount = data.optString("realRepayAmount","")
        binding.orderPayProcessAmount.text = realRepayAmount
        binding.orderPayProcessProductName.text = data.optString("product","")

        binding.orderPayProcessReason.text = String.format(getString(R.string.loan_payment_status_processed_reason1),realRepayAmount)

        countdown = 0
        showOrderPayProcessStatus()
        //是否开启倒计时
        if (data.optBoolean("isStartCountdown",true)){
            startOrderPayProcessTimeThread()
        }
    }

    /**
     * 启动倒计时
     */
    private fun startOrderPayProcessTimeThread() {
        if (timeThread != null) {
            timeThread!!.stopThread()
        }
        countdown = 30
        showOrderPayProcessStatus()
        if (timeThread == null) {
            timeThread = TimingThread()
            timeThread!!.setThreadDelayMillis(1000)
            timeThread!!.setLoadListener(this)
        }
        timeThread!!.startThread()
    }

    /**
     * 倒计时
     */
    override fun onLoading() {
        if (countdown <= 0) {
            countdown = 30
            timeThread!!.stopThread()

            if (act != null){
                //倒计时结束，自动调一次状态查询接口
                act!!.presenter!!.loadOrderPaymentPinStatusAction(false)
            }
            return
        }
        countdown--
        showOrderPayProcessStatus()
    }

    /**
     * 设置按钮状态
     */
    private fun showOrderPayProcessStatus(){
        if (countdown <= 0){
            binding.orderPayProcessPaymentAgain.isEnabled = true
            binding.orderPayProcessPaymentAgain.isClickable = true
            binding.orderPayProcessPaymentAgain.text = String.format(getString(R.string.loan_payment_status_make_payment_again),"")
        } else {
            binding.orderPayProcessPaymentAgain.isEnabled = false
            binding.orderPayProcessPaymentAgain.isClickable = false
            binding.orderPayProcessPaymentAgain.text = String.format(getString(R.string.loan_payment_status_make_payment_again),"(${countdown}s)")
        }
    }

    override fun onStart() {
        super.onStart()
        if (act != null){
            appEventPointRequestAction(AppEventPointType.PAGE.SHIPWE_PAGE_LOAN_PIN_REPAYMENT_PROCESS_START,act!!.getOrderPayProductName())
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        if (act != null){
            appEventPointRequestAction(AppEventPointType.PAGE.SHIPWE_PAGE_LOAN_PIN_REPAYMENT_PROCESS_END,act!!.getOrderPayProductName())
        }
        if (timeThread != null) {
            timeThread!!.stopThread()
            timeThread = null
        }
    }
}